/***
 Metronic AngularJS App Main Script
 ***/

/* Metronic App */
var App = angular.module("App", [
    "ui.router",
    "ui.bootstrap",
    "ngCookies",
    "angularFileUpload",
    "oc.lazyLoad",
    "ngSanitize",
    'ngAria',
    'w5c.validator'
]);


/* Configure ocLazyLoader(refer: https://github.com/ocombe/ocLazyLoad) */
App.config(['$ocLazyLoadProvider', function($ocLazyLoadProvider) {
    $ocLazyLoadProvider.config({
        // global configs go here
    });
}]);


//AngularJS v1.3.x workaround for old style controller declarition in HTML
App.config(['$controllerProvider', function($controllerProvider) {
    // this option might be handy for migrating old apps, but please don't use it
    // in new ones!
    $controllerProvider.allowGlobals();
}]);

//配置全局校验信息
App.config(["w5cValidatorProvider", function (w5cValidatorProvider) {

    // 全局配置
    w5cValidatorProvider.config({
        blurTrig   : true,
        showError  : true,
        removeError: true
    });

}]);

// 添加网络请求拦截
App.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    $httpProvider.interceptors.push('HttpInterceptor');
    $httpProvider.interceptors.push('AuthInterceptor');
}]);

/********************************************
 END: BREAKING CHANGE in AngularJS v1.3.x:
 *********************************************/

/* Setup global settings */
App.factory('settings', ['$rootScope', 'Page', function($rootScope, Page) {
    // supported languages
    var settings = {
        layout: {
            pageSidebarClosed: false, // sidebar menu state
            pageBodySolid: false, // solid body color state
            pageAutoScrollOnLoad: 500 // auto scroll to top on page load
        },
        layoutImgPath: Metronic.getAssetsPath() + 'admin/layout/img/',
        layoutCssPath: Metronic.getAssetsPath() + 'admin/layout/css/'
    };

    $rootScope.settings = settings;

    Page.ajaxPostQuiet('system/setting.do', null, function(resp) {
        $rootScope.projectName = resp.data.projectName;
        $rootScope.loginCaptcha = resp.data.loginCaptcha;
        $rootScope.nginxPath = resp.data.nginxPath;
    });

    return settings;
}]);


App.factory('HttpInterceptor',['$rootScope', function($rootScope) {
    // ---
    // PRVIATE METHODS.
    // ---
    // I serialize the given Object into a key-value pair string. This
    // method expects an object and will default to the toString() method.
    // --
    // NOTE: This is an atered version of the jQuery.param() method which
    // will serialize a data collection for Form posting.
    // --
    // https://github.com/jquery/jquery/blob/master/src/serialize.js#L45
    function serializeData(data) {
        // If this is not an object, defer to native stringification.
        if (!angular.isObject(data)) {
            return ((data == null) ? "" : data.toString());
        }
        var buffer = [];
        // Serialize each key in the object.
        for (var name in data) {
            if (!data.hasOwnProperty(name)) {
                continue;
            }
            var value = data[name];
            if (angular.isObject(value)) {
                value = angular.toJson(value);
            }
            buffer.push(encodeURIComponent(name) + "=" + encodeURIComponent((value == null) ? "" : value));
        }
        // Serialize the buffer and clean it up for transportation.
        var source = buffer.join("&").replace(/%20/g, "+");
        return (source);
    }
    return {
        request: function(config) {
            if (config.data && angular.isObject(config.data)) {
                if (config.method === 'POST') {
                    config.data = serializeData(config.data);
                } else if (config.method === 'GET') {
                    config.url += (config.url.indexOf('?') > 0 ? '&' : '?') + serializeData(config.data);
                }
            }
            config.headers._mId = $rootScope.menuId;// 当前菜单
            return config;
        }
    };
}])

/* 登录拦截器 */
App.factory('AuthInterceptor', ["$q", "$rootScope",function ($q, $rootScope) {
    return {
        request:function(config){
            //if ($rootScope.user) {
            //    config.headers["TOKEN"] = $rootScope.user.token;
            //}
            return config;
        },
        responseError: function (response) {
            if (response.status == 871202) {// 如果是登录超时

                delete $rootScope.user;
                $rootScope.$emit("userLoginIntercepted", response);
            }
            return $q.reject(response);
        }
    };
}]);

/* Setup App Main Controller */
App.controller('AppController', ['$scope', '$rootScope', '$state', '$timeout', function($scope, $rootScope, $state, $timeout) {
    $scope.$on('$viewContentLoaded', function() {
    	$timeout(function() {
       	 	Metronic.initComponents();
      	},0);
         // init core components
        //Layout.init(); //  Init entire layout(header, footer, sidebar, etc) on page load if the partials included in server side instead of loading with ng-include directive
    });
}]);

/***
 Layout Partials.
 By default the partials are loaded through AngularJS ng-include directive. In case they loaded in server side(e.g: PHP include function) then below partial
 initialization can be disabled and Layout.init() should be called on page load complete as explained above.
 ***/

/* Setup Layout Part - Header */
App.controller('HeaderController', ['$rootScope', '$scope', '$state', 'Page', function($rootScope, $scope, $state, Page) { 
	$scope.$on('$includeContentLoaded', function() {
        Layout.initHeader(); // init header
    });
    $scope.logout = function() {
        Page.ajaxPost('user/logout.do', null, function(resp) {
            delete $rootScope.user;
       		$state.go("index",null,{reload:true});
        });
    },
    $scope.logon = function() {
        delete $rootScope.user;
        $state.go("login",null,{reload:true});
    }

    $rootScope.$on('userLoginIntercepted', function(event, data) {
        $state.go("index",null,{reload:true});
    });
}]);

/* Setup Layout Part - Sidebar */
App.controller('SidebarController', ['$rootScope', '$scope', function($rootScope, $scope) {
    $scope.$on('$includeContentLoaded', function() {
        Layout.initSidebar(); // init sidebar
    });
}]);

/* Setup Layout Part - Footer */
App.controller('FooterController', ['$scope', function($scope) {
    $scope.$on('$includeContentLoaded', function() {
        Layout.initFooter(); // init footer
    });
}]);

/* 登录 */
App.controller('LoginController', ["$rootScope", '$scope', '$state', '$window', 'Page', 'XCode', 'router',
    function($rootScope, $scope, $state, $window, Page, XCode, router) {
	
        $scope.$on('$viewContentLoaded', function() {
            $scope.timestamp = Math.random();
        });

        var validator = $scope.validator = {
            htmlSource        : "",
            showErrorType     : 1,
            showDynamicElement: true
        };

        validator.login = function () {
            if($scope.validateForm.$valid){
                var data = {userCode: $scope.userCode, password: $scope.password, captcha: $scope.captcha};

                Page.ajaxPost('user/login.do', data, function (resp) {
                    if(resp.data.user.sourceId && resp.data.user.sourceId != ''){
                    	Page.ajaxPostQuiet('customer/' +  resp.data.user.sourceId + '/info.do', null, function (_resp) {
	                		$rootScope.user = resp.data.user;
	                		$rootScope.user.customer = _resp.data;
		
		                    if($state.params.toState && $state.params.toState.name){
								$state.go($state.params.toState.name, $state.params.toState.params,{reload:true});
							}else{
								$state.go('index',null,{reload:true});
							}
					 	}, function (data) {
					 		delete $rootScope.user;
		                    $('#errorDiv').show();
	                		$('#errorInfo').html("账号信息不存在!");
		                });
                    }else{
                    	delete $rootScope.user;
                    	$('#errorDiv').show();
	                	$('#errorInfo').html("账号信息不存在!");
                    }
                }, function (data) {
                    $('#errorDiv').show();
                    $('#errorInfo').html(data.resultDes);
                    //changeCaptcha();
                });
            }
        };

        //每个表单的配置，如果不设置，默认和全局配置相同
        validator.validateOptions = {
            blurTrig: true
        };
    }]);

/* Init global settings and run the app */
App.run(["$rootScope", "settings", "$state", '$window', 'XCode', 'router', 'Page','$interval', function($rootScope, settings, $state, $window, XCode, router,Page,$interval) {
    $rootScope.$state = $state; // state to be accessed from view
    XCode.init();
    $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
    	if(fromState.name == 'bid'){// 离开竞价页面，去掉该页面的自动刷新的函数
			$interval.cancel($rootScope.timer); // 终止函数执行
			$interval.cancel($rootScope.timerX); // 终止函数执行
		}
        if (toState.name == 'login') {
			delete $rootScope.user;// 清空菜单
		} else if (toState.auth && !$rootScope.user) {
			event.preventDefault();// 取消默认跳转行为
			toState.params = toParams;
			toParams.toState = toState;
			$state.go("login", {'toState' : toState});
		}       
    });
    
    if ($window.location.href.indexOf('#') > 0 && $window.location.href.indexOf('#/login.html') < 0) {
        $.ajax({
            url : 'user/refresh.do',
            method: 'POST',
            async: false,
            success : function(resp){
                $rootScope.$apply(function() {
                	if(!resp.data || !resp.data.sourceId || resp.data.sourceId == '' || resp.data.type != '2'){
                    	
                    }else{
                    	$rootScope.user = resp.data;
                    	Page.ajaxPostQuiet('customer/' +  $rootScope.user.sourceId + '/info.do', null, function (_resp) {
                    		$rootScope.user.customer = _resp.data;
		                    // 初始化下拉列表
		 					setTimeout(function () {
                        		Layout.setMainMenuActiveLink('match'); // activate selected link in the sidebar menu
                    		}, 1500);
					 	}, function (data) {
					 		delete $rootScope.user;
		                });
                    }
                });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
            	
            } 
        });
    }

    
}]);